package cn.tedu.controller;

import cn.tedu.entity.User;
import cn.tedu.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户注册
 *
 * @author waqwb
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("注册请求被执行了");

        /*
         * 1.获取参数
         * 2.调用service处理
         * 3.返回结果
         * */
        req.setCharacterEncoding("UTF-8");
        User user = new User();
        user.setEmail(req.getParameter("email"));
        user.setNickname(req.getParameter("nickname"));
        user.setPassword(req.getParameter("password"));

        // 保存数据
        int row = userService.saveUser(user);

        // 返回结果
        if (row > 0) {
            //跳转注册成功界面
            HttpSession session = req.getSession();
            session.setAttribute("nickname", user.getNickname());
            session.setAttribute("email", user.getEmail());
            req.setAttribute("message", "注册成功");
            resp.sendRedirect("register_ok2.jsp");
        } else {
            // 跳转注册界面，并提示错误信息
            req.setAttribute("errorMsg", "注册失败，请稍后再试！");
            req.getRequestDispatcher("register.jsp").forward(req, resp);
        }
    }
}
